import validate from 'wechat-validate'
Page({
  behaviors: [validate],
  data: {
    dateLayerVisible: false,
    houseLayerVisible: false,
    houseList: [], //房屋列表
    houseInfo: '',
    houseId: '',
    name: '',
    gender: 1,
    mobile: '',
    visitDate: '',
    currentDate: +new Date(), // 当前日期和最小的访问日期
    maxDate: +new Date() + 3 * 24 * 60 * 60 * 1000 // 最大访问日期
  },
  rules: {
    houseId: [{
      required: true,
      message: '请选择房屋信息'
    }],
    name: [{
        required: true,
        message: '请输入访客姓名'
      },
      {
        pattern: /^(?:[\u4e00-\u9fa5·]{2,16})$/,
        message: '请输入中文姓名'
      }
    ],
    mobile: [{
        required: true,
        message: '请输入手机号'
      },
      {
        pattern: /^1[3-9]\d{9}$/,
        message: '请输入合法的11位手机号'
      }
    ],
    visitDate: [{
      required: true,
      message: '请选择到访日期'
    }]
  },
  // 控制房屋的动作面板
  openHouseLayer() {
    this.setData({
      houseLayerVisible: true
    })
  },
  closeHouseLayer() {
    this.setData({
      houseLayerVisible: false
    })
  },
  onShow() {
    this.getHouse()
  },
  // 获取审核通过的房屋列表
  async getHouse() {
    const res = await wx.http.get('/house')
    this.setData({
      houseList: res.data
    })
  },
  // 获取选中的房屋
  selectHouse(ev) {
    // console.log(ev);
    this.setData({
      houseId: ev.detail.id, // 用于提交的
      houseInfo: ev.detail.name // 用于展示的
    })
  },

  // 控制选择日期的动作面板
  openDateLayer() {
    this.setData({
      dateLayerVisible: true
    })
  },
  closeDateLayer() {
    this.setData({
      dateLayerVisible: false
    })
  },
  // 选择预约日期
  seleteDate(e) {
    this.setData({
      visitDate: wx.utils.formatTime(e.detail),
      dateLayerVisible: false
    })
  },
  // 生成访客邀请
  async goPassport() {
    // 1. 预校验
    if (!this.validate()) return
    // 2. 发送请求
    const {
      houseId,
      name,
      mobile,
      gender,
      visitDate
    } = this.data
    const res = await wx.http.post('/visitor', {
      houseId,
      name,
      mobile,
      gender,
      visitDate
    })
    // 3. 跳转
    wx.reLaunch({
      url: '/visitor_pkg/pages/passport/index?id=' + res.data.id,
    })
  },
})